    //
//  OrderViewController.m
//  Order
//
//  Created by funny on 12-3-21.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "OrderViewController.h"

#import "OrderDB.h"

#import "AsyncUdpSocket.h"
#import "AsyncSocket.h"

#import "UserDBManager.h"

#import "SHKActivityIndicator.h"

#define SERVER_IP    @"192.168.1.100"
#define SERVER_PORT  9527

#define ORDER_CONTENT_FORMAT @"        高八斗\n工号:%d\n桌号:%@\n时间:%@\n--------------------------------------------\n品名                     份数        \n--------------------------------------------\n%@------------------谢谢惠顾--------------------\n"

@implementation OrderViewController

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	sendSucess = NO;
	
	self.title = @"点菜界面";
	
	orderContent = [[NSMutableArray alloc] init];
	[orderContent addObject:[OrderDB orderDBWithName:@"骨头汤" andPackagePrice:12.0f andSinglePrice:8.0f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"鸭腿" andPackagePrice:14.0f andSinglePrice:9.0f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"大排" andPackagePrice:15.0f andSinglePrice:10.0f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"鸡腿" andPackagePrice:15.0f andSinglePrice:5.0f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"小排" andPackagePrice:16.0f andSinglePrice:11.0f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"猪蹄" andPackagePrice:16.0f andSinglePrice:11.0f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"狮子头" andPackagePrice:16.0f andSinglePrice:5.5f]];
	[orderContent addObject:[OrderDB orderDBWithName:@"仔鸡" andPackagePrice:15.0f andSinglePrice:10.0f]];
	
	UIControl *headerView = [[[UIControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 1024.0f, 65.0f)] autorelease];
	headerView.backgroundColor = [UIColor grayColor];
	[headerView addTarget:self action:@selector(backTap:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:headerView];
	
	UILabel *deskNumLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20.0f, 10.0f, 80.0f, 30.0f)] autorelease];
	deskNumLabel.text = @"桌号：";
	deskNumLabel.backgroundColor= [UIColor clearColor];
	deskNumLabel.font = [UIFont systemFontOfSize:25.0f];
	deskNumLabel.textAlignment = UITextAlignmentCenter;
	[headerView addSubview:deskNumLabel];
	
	deskNumTextField = [[[UITextField alloc] initWithFrame:CGRectMake(100.0f, 10.0f, 60.0f, 30.0f)] autorelease];
	deskNumTextField.placeholder = @"";
	deskNumTextField.borderStyle = UITextBorderStyleRoundedRect;
	deskNumTextField.font = [UIFont systemFontOfSize:25.0f];
	deskNumTextField.textAlignment = UITextAlignmentRight;
	deskNumTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
	[headerView addSubview:deskNumTextField];
	
	UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[clearBtn setTitle:@"清空" forState:UIControlStateNormal];
	clearBtn.titleLabel.font = [UIFont systemFontOfSize:25.0f];
	clearBtn.frame = CGRectMake(720.0f, 10.0f, 80.0f, 30.0f);
	[clearBtn addTarget:self action:@selector(clearOrder:) forControlEvents:UIControlEventTouchUpInside];
	[headerView addSubview:clearBtn];
	
	UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
	confirmBtn.titleLabel.font = [UIFont systemFontOfSize:25.0f];
	confirmBtn.frame = CGRectMake(820.0f, 10.0f, 80.0f, 30.0f);
	[confirmBtn addTarget:self action:@selector(confirmOrder:) forControlEvents:UIControlEventTouchUpInside];
	[headerView addSubview:confirmBtn];
	
	UIButton *previewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[previewBtn setTitle:@"预览" forState:UIControlStateNormal];
	previewBtn.titleLabel.font = [UIFont systemFontOfSize:25.0f];
	previewBtn.frame = CGRectMake(920.0f, 10.0f, 80.0f, 30.0f);
	[previewBtn addTarget:self action:@selector(previewOrder:) forControlEvents:UIControlEventTouchUpInside];
	[headerView addSubview:previewBtn];
	
	
	orderTable = [[[UITableView alloc] initWithFrame:CGRectMake(0.0f, 65.0f, self.view.frame.size.width, self.view.frame.size.height - 65.0f) style:UITableViewStylePlain] autorelease];
	orderTable.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	[self.view addSubview:orderTable];
	orderTable.delegate = self;
	orderTable.dataSource = self;
}

- (void)backTap:(id)sender{
	[deskNumTextField resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	
	[self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController setToolbarHidden:NO animated:YES];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[orderContent release];
	
    [super dealloc];
}

/*
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return 100.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
	UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 1024.0f, 100.0f)] autorelease];
	headerView.backgroundColor = [UIColor blueColor];
	
	return headerView;
}
*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	return 1;
}

- (NSInteger)tableView : (UITableView *) tableView numberOfRowsInSection : (NSInteger) section{ 
    return orderContent.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 120.0f;
}

- (UITableViewCell *)tableView : (UITableView *)tableView cellForRowAtIndexPath : (NSIndexPath *)indexPath{ 
    static NSString *OrderCellIdentifier = @"OrderCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OrderCellIdentifier]; 
	
	NSUInteger row = [indexPath row];
	
    if(cell == nil){
        cell = [[[OrderCell alloc] initWithFrame:CGRectZero reuseIdentifier:OrderCellIdentifier] autorelease];
		((OrderCell *)cell).orderDelegate = self;
    }
	
	if ([cell isKindOfClass:[OrderCell class]] && row < orderContent.count) {
		OrderDB *nowOrderDB = [orderContent objectAtIndex:row];
		
		((OrderCell *)cell).row = row;
		[((OrderCell *)cell) refreshWithName:nowOrderDB.name andPackageCount:nowOrderDB.packageCount andSingleCount:nowOrderDB.singleCount];
	}
	
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
	[deskNumTextField resignFirstResponder];
}

- (void)OrderCellDelegate:(OrderCell *)orderCell packageCountDidChangeTo:(NSInteger)packageCount inRow:(NSInteger)row{
	[deskNumTextField resignFirstResponder];
	
	if (row < orderContent.count) {
		OrderDB *nowOrderDB = [orderContent objectAtIndex:row];
		
		[nowOrderDB setPackageCount:packageCount];
	}
}

- (void)OrderCellDelegate:(OrderCell *)orderCell singleCountDidChangeTo:(NSInteger)singleCount inRow:(NSInteger)row{
	[deskNumTextField resignFirstResponder];
	
	if (row < orderContent.count) {
		OrderDB *nowOrderDB = [orderContent objectAtIndex:row];
		
		[nowOrderDB setSingleCount:singleCount];
	}
}

- (void)resetCount{
	for (OrderDB *nowOrderDB in orderContent) {
		[nowOrderDB resetCount]; 
	}
}

- (float)calculateTotalPrice{
	float totalPrice;
	
	for (OrderDB *nowOrderDB in orderContent) {
		totalPrice += [nowOrderDB calculateTotalPrice]; 
	}
	
	//NSLog(@"calculateTotalPrice : %f", totalPrice);
	
	return totalPrice;
}

- (void)clearOrder:(id)sender{
	[deskNumTextField resignFirstResponder];
	
	[self resetCount];
	[orderTable reloadData];
}

- (NSString *)orderString{
	NSMutableString *orderDataString = [[[NSMutableString alloc] init] autorelease];
	for (OrderDB *nowOrderDB in orderContent) {
		if (nowOrderDB.packageCount > 0) {
			[orderDataString appendString:[NSString stringWithFormat:@"%@           %d\n", nowOrderDB.name, nowOrderDB.packageCount]];
		}
		if (nowOrderDB.singleCount > 0) {
			[orderDataString appendString:[NSString stringWithFormat:@"%@           %d\n", nowOrderDB.name, nowOrderDB.packageCount]];
		}
	}
	[orderDataString appendString:[NSString stringWithFormat:@"\n总价：           %0.2f\n", [self calculateTotalPrice]]];
	
	NSDateFormatter *dateformat=[[[NSDateFormatter alloc] init] autorelease];
	[dateformat setFormatterBehavior:NSDateFormatterFullStyle];	
	[dateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	
	return [NSString stringWithFormat:ORDER_CONTENT_FORMAT, [[UserDBManager sharedUserDBManager] nowUserID], [deskNumTextField text], [dateformat stringFromDate:[NSDate date]], orderDataString];
}

- (void)confirmOrder:(id)sender{
	[deskNumTextField resignFirstResponder];
	
	NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
	NSMutableData *data = [NSMutableData dataWithData:[[self orderString] dataUsingEncoding:enc]];
    
	//NSLog(@"data : %@", [[[NSString alloc] initWithData:data encoding:enc] autorelease]);
	
    char a = (char)29;
    char b = (char)86;
    char c = (char)66;
    char d = (char)30;
	[data appendBytes:&a length:1];
	[data appendBytes:&b length:1];
    [data appendBytes:&c length:1];
    [data appendBytes:&d length:1];
	
    static BOOL connectOK = NO;
	
    if (!sendSocket)
    {
        sendSocket = [[AsyncSocket alloc] initWithDelegate: self];
		
        NSError *error;
        connectOK = [sendSocket connectToHost: SERVER_IP onPort: SERVER_PORT error: &error];
		
        if (!connectOK)
        {
            NSLog(@"connect error: %@", error);
			
			UIAlertView *alert=[[[UIAlertView alloc] initWithTitle:@"打印失败" message:@"连接失败！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
			[alert show];
        }
		
        [sendSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    }
	
    if (connectOK) 
    {
		sendSucess = NO;
		
        [sendSocket writeData: data withTimeout: -1 tag: 0];
        [sendSocket disconnectAfterWriting];
		
		[[SHKActivityIndicator currentIndicator] displayActivity: @"小票打印中..."];
    }
}

- (void)previewOrder:(id)sender{
	[deskNumTextField resignFirstResponder];
	
	UIViewController *previewController = [[[UIViewController alloc] init] autorelease];
	previewController.view.frame = CGRectMake(0.0f, 0.0f, 500.0f, 600.0f);
	
	UITextView *previewText = [[[UITextView alloc] initWithFrame:previewController.view.bounds] autorelease];
	previewText.text = [self orderString];
	previewText.font = [UIFont systemFontOfSize:30.0f];
	previewText.editable = NO;
	//previewText.userInteractionEnabled = NO;
	[previewController.view addSubview:previewText];
	
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:previewController];
    popover.popoverContentSize = CGSizeMake(500.0f, 600.0f);
    [popover presentPopoverFromRect:CGRectMake(960.0f, 30.0f, 10.0f, 10.0f) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
	NSLog(@"%s %d", __FUNCTION__, __LINE__);
	
    [sendSocket readDataWithTimeout: -1 tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"%s %d, tag = %ld", __FUNCTION__, __LINE__, tag);
	
    [sendSocket readDataWithTimeout: -1 tag: 0];
	
	sendSucess = YES;
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *msg = [[[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding] autorelease];
	
    NSLog(@"%s %d, msg = %@", __FUNCTION__, __LINE__, msg);
	
    [sendSocket readDataWithTimeout: -1 tag: 0];
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"%s %d", __FUNCTION__, __LINE__);
	
	[sendSocket release];
    sendSocket = nil;
	
	[[SHKActivityIndicator currentIndicator] hide];
	
	if (sendSucess) {
		[self clearOrder:nil];
		deskNumTextField.text = @"";
	}
	else {
		UIAlertView *alert=[[[UIAlertView alloc] initWithTitle:@"打印失败" message:@"发送失败！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
		[alert show];
	}
}

@end
